//
//  BaseVC.m
//  TuYouAPP
//
//  Created by L on 14-2-18.
//
//

#import "BaseVC.h"
#import "MTA.h"
#import "MTAConfig.h"
#import "DataModel.h"
#import "MySelfInfoVC.h"
#import "DynamicReplyVC.h"
@interface BaseVC ()
{
    
}
@end
#define REFRESH_HEADER_HEIGHT 48.0f
@implementation UINavigationController (Rotation_IOS6)

-(BOOL)shouldAutorotate
{
    return [[self.viewControllers lastObject] shouldAutorotate];
}

-(NSUInteger)supportedInterfaceOrientations
{
    return [[self.viewControllers lastObject] supportedInterfaceOrientations];
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}

@end
@implementation BaseVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return nil;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 0;
}

- (NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navBar.titleLabel.hidden = NO;

    self.navBar.titleLabel.hidden = NO;
    
    self.navigationController.navigationBarHidden = YES;
    [UIApplication sharedApplication].statusBarHidden = YES;

}
-(void)loadView
{
    [super loadView];
    self.tableview = [[UITableView alloc]init];
    
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.navBar =  [[NavBar alloc]initWithIsBackImage:self.isBackBtn];
    self.navBar.NavDelegate = self;
    [self.view addSubview:self.navBar];
    self.navigationController.navigationBar.frame=CGRectMake(0, -43, 320, 44);
    self.self.navigationController.navigationBar.backgroundColor = [UIColor grayColor];
    [self.view bringSubviewToFront:self.navBar];
}
-(void)loadPullRefreshView
{
    [self addPullToRefreshFooter];
    self.textPull    = @"上滑查看更多...";
    self.textRelease = @"释放开始刷新...";
    self.textLoading = @"正在加载...";
    self.textNoMore  = @"没有更多内容了...";
    self.hasMore = YES;

}

-(void)addPullToRefreshFooter{
    self.refreshFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 48)];
    self.refreshFooterView.backgroundColor = [UIColor clearColor];
    
   self. refreshLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
   self. refreshLabel.backgroundColor = [UIColor clearColor];
   self. refreshLabel.font = [UIFont boldSystemFontOfSize:12.0];
   self. refreshLabel.textAlignment = UITextAlignmentCenter;
   self. refreshLabel.text =  @"上滑查看更多...";
    
    
   self. refreshSpinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
   self. refreshSpinner.frame = CGRectMake(floorf(floorf(REFRESH_HEADER_HEIGHT - 20) / 2), floorf((REFRESH_HEADER_HEIGHT - 20) / 2), 20, 20);
   self. refreshSpinner.hidesWhenStopped = YES;
    
    [self.refreshFooterView addSubview:self.refreshLabel];
    [self.refreshFooterView addSubview:self.refreshSpinner];
  //  self.refreshFooterView.backgroundColor = [UIColor redColor];
    self.tableview.tableFooterView = self.refreshFooterView;
}

-(void)viewDidAppear:(BOOL)animated
{
    [MTA trackPageViewBegin:_mPageName];
    
    if( E_NotGoto == [GInfo shareClient].mgoto ) return;
    
    GotoPage p = [GInfo shareClient].mgoto;
    [GInfo shareClient].mgoto = E_NotGoto;
    NSString* j = [GInfo shareClient].mojid;
    [GInfo shareClient].mojid = nil;
    
    switch ( p ) {
            
        case E_ReBackMe:
        case E_ReBackMyStatus:
        {
            MySelfInfoVC* my = [[MySelfInfoVC alloc] initWithNibName:@"MySelfInfoVC" bundle:nil];
            [self.navigationController pushViewController:my
                                                 animated:YES];
            break;
        }
        case E_StatusDetail:
        {
            if( j )
            {
                [SVProgressHUD showWithStatus:@"加载中"];
                [TYUserState getOneStatus:[GInfo shareClient].mojid callback:^(TYUserState *one, NSString *err) {
                    
                    if( one )
                    {
                        [SVProgressHUD dismiss];
                        DynamicReplyVC* dy = [[DynamicReplyVC alloc]  init];
                        dy.thePublish = one;
                        [self.navigationController pushViewController:dy
                                                         animated:YES];
                    }
                    else
                    {
                        [SVProgressHUD showErrorWithStatus:@"加载失败"];
                    }
                }];
            }
            break;
        }
        default:
            break;
    }
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navBar.titleLabel.hidden = YES;

}
-(void)viewDidDisappear:(BOOL)animated
{
     [MTA trackPageViewEnd:_mPageName];
}

-(void)setTitle:(NSString *)test
{
    self.navBar.titleLabel.text = test;
}
-(void)setRightBarTitle:(NSString *)title
{
    CGSize constraint = CGSizeMake(280, CGFLOAT_MAX);
    CGSize size = [title sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];

    CGRect rect = self.navBar.rightBtn.frame;
    rect.size.width = size.width+30;
    rect.origin.x = DEVICE_Width-size.width-35;
    self.navBar.rightBtn.frame = rect;
    [self.navBar.rightBtn setTitle:title forState:UIControlStateNormal];
}
-(void)setLeftBarTitle:(NSString *)title
{
    [self.navBar.leftBtn setTitle:title forState:UIControlStateNormal];
}


-(void)initWithRefreshTableViewIos7:(CGRect)rect Ios6rect:(CGRect)rect1
{
    
    
    if (SystemIsiOS7()) {
        self.tableview.frame = rect;
        self.automaticallyAdjustsScrollViewInsets = NO;

    }
    else
    {
        self.tableview .frame = rect1;
        
    }
    
    if (self.haveFullupRefreshView == YES) {
        [self loadPullRefreshView];
    }

    self.slimeView = [[SRRefreshView alloc] init];
    _slimeView.delegate = self;
    _slimeView.upInset = 0;
    _slimeView.slimeMissWhenGoingBack = YES;
    _slimeView.slime.bodyColor = [UIColor blackColor];
    _slimeView.slime.skinColor = [UIColor whiteColor];
    _slimeView.slime.lineWith = 1;
    _slimeView.slime.shadowBlur = 4;
    _slimeView.slime.shadowColor = [UIColor blackColor];
    [self.tableview addSubview:_slimeView];
    [self.view addSubview:self.tableview];

}


#pragma mark - scrollView delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_slimeView scrollViewDidScroll];

    if (isLoading && scrollView.contentOffset.y > 0) {
        // Update the content inset, good for section headers
        self.tableview.contentInset = UIEdgeInsetsMake(0, 0, REFRESH_HEADER_HEIGHT, 0);
    }else if(!self.hasMore){
        self.refreshLabel.text = self.textNoMore;
    }else if (isDragging && scrollView.contentSize.height - (scrollView.contentOffset.y + scrollView.bounds.size.height ) <= 0 ) {
        // Update the arrow direction and label
        [UIView beginAnimations:nil context:NULL];
        if (scrollView.contentSize.height - (scrollView.contentOffset.y + scrollView.bounds.size.height - scrollView.contentInset.bottom+500) >= -REFRESH_HEADER_HEIGHT) {
            // User is scrolling above the header
            self.refreshLabel.text = self.textRelease;
        } else { // User is scrolling somewhere within the header
            //self.refreshLabel.text = self.textPull;
        }
        [UIView commitAnimations];
    }

    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    
    [_slimeView scrollViewDidEndDraging];

    if (isLoading || !self.hasMore) return;
    isDragging = NO;
    
    //上拉刷新
    if(scrollView.contentSize.height - (scrollView.contentOffset.y + scrollView.bounds.size.height - scrollView.contentInset.bottom) <= -REFRESH_HEADER_HEIGHT && scrollView.contentOffset.y > 0){
        [self startLoading];
    }

}

#pragma mark - slimeRefresh delegate

- (void)slimeRefreshStartRefresh:(SRRefreshView *)refreshView
{
    [_slimeView performSelector:@selector(endRefresh)
                     withObject:nil afterDelay:3
                        inModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
}
-(void)leftBtnTouched:(id)sender
{
    
}
-(void)rightBtnTouched:(id)sender
{
    
}
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
     assert(_mPageName);
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    
    
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (isLoading) return;
    isDragging = YES;
}




- (void)startLoading {
    isLoading = YES;
    
    // Show the header
    [UIView beginAnimations:nil context:NULL];
    self.tableview.contentInset = UIEdgeInsetsMake(REFRESH_HEADER_HEIGHT, 0, 0, 0);

    [UIView setAnimationDuration:0.3];
    self.refreshLabel.text = self.textLoading;
    [self.refreshSpinner startAnimating];
    //self.tableview.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);

    [UIView commitAnimations];
    
    // Refresh action!
    [self refresh];
}

- (void)stopLoading {
    isLoading = NO;
    
    // Hide the header
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationDidStopSelector:@selector(stopLoadingComplete:finished:context:)];
  //  self.tableview.contentInset = UIEdgeInsetsZero;
    UIEdgeInsets tableContentInset = self.tableview.contentInset;
    tableContentInset.bottom = 0.0;
    self.tableview.contentInset = tableContentInset;
    [UIView commitAnimations];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}
- (void)stopLoadingComplete:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
    // Reset the header
   // NSLog(@"%f",self.tableview.contentSize.height);
    
  // self.refreshLabel.text = self.textPull;
    
   // [self.refreshFooterView setFrame:CGRectMake(0, self.tableview.contentSize.height, 320, 0)];
    
    [self.refreshSpinner stopAnimating];
}

- (void)refresh {
    // This is just a demo. Override this method with your custom reload action.
    // Don't forget to call stopLoading at the end.
    [self performSelector:@selector(stopLoading) withObject:nil afterDelay:2.0];
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
